package com.example.bysj_sb.dao;

import com.example.bysj_sb.domain.*;
import com.example.bysj_sb.service.StudentClassService;
import com.example.bysj_sb.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository("studentDao")
public class StudentDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private StudentClassService studentClassService;
    @Autowired
    private TeacherService teacherService;
    //增加
    public boolean add(Student student) {
        String sql = "INSERT INTO student (name,no,studentClass_id) VALUES (?,?,?)";
        int affectedRowNum = jdbcTemplate.update(sql, student.getName(),
                student.getNo(),student.getStudentClass().getId());
        if (affectedRowNum != 1) {
            return false;
        } else {
            return true;
        }
    }
    //通过定义内部类来返回查询结果
    public class StudentRowMapper implements RowMapper<Student> {
        @Override
        public Student mapRow(ResultSet resultSet, int i) throws SQLException {
            Student student = new Student();
            student.setId(resultSet.getInt("id"));
            student.setName(resultSet.getString("name"));
            student.setNo(resultSet.getString("no"));
            StudentClass studentClass =
            studentClassService.find(resultSet.getInt("studentClass_id"));
            student.setStudentClass(studentClass);
            Teacher teacher = teacherService.find(resultSet.getInt("teacher_id"));
            student.setSupervisor(teacher);
            return student;
        }
    }

    public Student find(int id){
        String sql = "SELECT * FROM student WHERE id = ?";
        List<Student> students = jdbcTemplate.query(sql, new Object[]{id}, new StudentRowMapper());
        if(!students.isEmpty()){
            return students.get(0);
        } else
            return null;
    }

    public List<Student> findAll(){
        String sql = "SELECT * FROM Student ";
        List<Student> students = jdbcTemplate.query(sql, new StudentRowMapper());
        return students;
    }
    public boolean update(Student student) {
        String sql = "UPDATE Student SET no = ? ,name=? WHERE id = ?";
        int affectedRowNum = jdbcTemplate.update(sql, student.getNo(), student.getName(), student.getId());
        if (affectedRowNum != 1) {
            return false;
        } else {
            return true;
        }
    }
    public boolean delete(int id){
        String sql = "DELETE FROM Student WHERE id = ? ";
        int affectedRowNum = jdbcTemplate.update(sql,id);
        if (affectedRowNum!=1){
            return false;
        }else{
            return true;
        }
    }
}
